/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml.beer;

import beans.Beer;
import java.beans.IntrospectionException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.betwixt.io.BeanWriter;
import org.xml.sax.SAXException;

public class BeerWriter {

    BeanWriter writer;
    FileOutputStream fos;
    StringWriter content;

    public BeerWriter() {
    }

    /**
     * print a new beer in xml file
     *
     * @param beer
     */
    public boolean print(Beer beer) {

        BeerReader beerReader = new BeerReader();
        List<Beer> allBeers = beerReader.getAllBeers();
        if (allBeers == null || allBeers.size() == 0) {
            allBeers = new ArrayList<>();
        }
        allBeers.add(beer);
        return printInXML(allBeers);
    }

    public boolean printAllBeers(List<Beer> beers) {
        return printInXML(beers);
    }

    private boolean printInXML(List<Beer> beers) {
        content = new StringWriter();
        content.write("<?xml version='1.0'?>\r\n");
        content.write("<beers>\r\n");
        try {
            writer = new BeanWriter(content);
            writer.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
            writer.enablePrettyPrint();
            writer.getBindingConfiguration().setMapIDs(false);
            writer.start();
            for (Beer b : beers) {
                writer.write(b);
            }
            writer.end();
            content.write("</beers>");
            System.out.println(content);
            File f = new File("src\\xml\\beer\\beers.xml");
            if (!f.exists()) {
                f.createNewFile();
            }
            PrintWriter out = new PrintWriter(f);
            out.print(content);
            out.flush();
            return true;
        } catch (IOException ex) {
            writer = null;
            ex.printStackTrace();
        } catch (SAXException ex) {
            Logger.getLogger(BeerWriter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IntrospectionException ex) {
            Logger.getLogger(BeerWriter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    public boolean remove(Beer b) {
        BeerReader beerReader = new BeerReader();
        List<Beer> allBeers = beerReader.getAllBeers();
        if (allBeers.contains(b)) {
            allBeers.remove(b);
        }else{
            return false;
        }
        return printAllBeers(allBeers);
    }
}
